package com.bknc.example;

import android.content.Context;
import android.util.Log;
import android.view.*;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.view.SurfaceHolder.Callback;
 
public class MainSurfaceView extends SurfaceView implements Callback, Runnable{
 
    private static final String LOG = "MainSurfaceView";
 
    private SurfaceHolder   mSurfaceHolder;
    private Thread          thread;
 
    public  Bitmap          bitmapImage;
 
    public MainSurfaceView(Context context) {
        super(context);
        Log.d(LOG, "MainSurfaceView is constructed(Context)");
        this.mSurfaceHolder = this.getHolder();
        this.initSurfaceHolder();
    }
 
    public MainSurfaceView(Context context, SurfaceView sv) {
        super(context);
        Log.d(LOG, "MainSurfaceView is constructed(Context, SurfaceView)");
        this.mSurfaceHolder = sv.getHolder();
        this.initSurfaceHolder();
    }
 
    private void initSurfaceHolder(){
        Log.d(LOG, "initSurfaceHolder method is fired");
        this.mSurfaceHolder.addCallback(this);
        Resources res = this.getContext().getResources();
        bitmapImage = BitmapFactory.decodeResource(res, R.drawable.bg);
        setFocusable(true);
        requestFocus();
    }
 
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height){
        Log.d(LOG, "surfaceChanged is fired");
        this.mSurfaceHolder.setFormat(PixelFormat.TRANSLUCENT);
    }
 
    public void surfaceCreated(SurfaceHolder holder){
        thread = new Thread(this);
        thread.start();             // must be located in surfaceCreated()
    }
    public void surfaceDestroyed(SurfaceHolder holder){
        thread = null;
    }
 
    public void run() {
        Log.d(LOG, "run is fired");
        Canvas c = this.mSurfaceHolder.lockCanvas();
        c.drawBitmap(this.bitmapImage, 0, 0, null);
        this.mSurfaceHolder.unlockCanvasAndPost(c);
    }
}
